<template>
  <a-form
      :model="ruleForm"
      ref="ruleForm"
      v-bind="layout"
      :rules="rules"
      @finish="handleFinish"
  >
    <a-form-item label="课题组名称" name="research_group_name">
      <a-input v-model:value="ruleForm.research_group_name"/>
    </a-form-item>
    <a-form-item label="责任人" name="research_group_principal">
      <a-select
          v-model:value="ruleForm.research_group_principal"
          style="width: 120px"
          ref="select"
      >
        <a-select-option
            v-for="item in research_group_principalSelectionOptions"
            :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="参与人" name="targetresearch_group_participantKeys">
      <a-transfer
          :data-source="ruleForm.research_group_participants"
          :titles="['未选择', '已选择']"
          :target-keys="ruleForm.targetresearch_group_participantKeys"
          :selected-keys="ruleForm.selectedresearch_group_participantKeys"
          :render="(item) => item.title"
          @change="handleChange"
          @selectChange="handleSelectChange"
          :locale="{
          itemUnit: '项',
          itemsUnit: '项',
          notFoundContent: '列表为空',
          searchPlaceholder: '请输入搜索内容',
        }"
      />
    </a-form-item>
    <!--    <a-form-item label="参与人" name="research_group_participant">-->
    <!--      <a-select-->
    <!--        v-model:value="ruleForm.research_group_participant"-->
    <!--        style="width: 120px"-->
    <!--        ref="select"-->
    <!--      >-->
    <!--        <a-select-option-->
    <!--          v-for="item in research_group_participantSelectionOptions"-->
    <!--          :key="item.url"-->
    <!--        >-->
    <!--          {{ item.label }}-->
    <!--        </a-select-option>-->
    <!--      </a-select>-->
    <!--    </a-form-item>-->
    <!--    <a-form-item label="审核人" name="research_group_reviewer">-->
    <!--      <a-select-->
    <!--        v-model:value="ruleForm.research_group_reviewer"-->
    <!--        style="width: 120px"-->
    <!--        ref="select"-->
    <!--      >-->
    <!--        <a-select-option-->
    <!--          v-for="item in research_group_reviewerSelectionOptions"-->
    <!--          :key="item.url"-->
    <!--        >-->
    <!--          {{ item.label }}-->
    <!--        </a-select-option>-->
    <!--      </a-select>-->
    <!--    </a-form-item>-->
    <a-form-item label="课题名称" name="subject_name">
      <a-select
          v-model:value="ruleForm.subject_name"
          style="width: 120px"
          ref="select"
      >
        <a-select-option
            v-for="item in subject_nameSelectionOptions"
            :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="团队名称" name="team_name">
      <a-select
          v-model:value="ruleForm.team_name"
          style="width: 120px"
          ref="select"
      >
        <a-select-option
            v-for="item in team_nameSelectionOptions"
            :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import {message} from 'ant-design-vue'

export default {
  name: 'AddorEditTeamInfo',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],
  data() {
    let validateresearch_group_principal = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择课题组负责人");
      }
    };
    let validateresearch_group_participant = async (rule, value) => {
      if (value.length === 0) {
        return Promise.reject("请选择课题组参与人");
      }
    };
    let validatesubject_name = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择课题名称");
      }
    };
    let validateteam_name = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择团队名称");
      }
    };
    return {
      ruleForm: {
        research_group_name: '',
        research_group_principal: '',
        // research_group_participant: '',
        // research_group_reviewer: '',
        research_group_participants: [],
        targetresearch_group_participantKeys: [],
        selectedresearch_group_participantKeys: [],
        subject_name: '',
        team_name: '',
      },
      rules: {
        research_group_principal: [
          {
            validator: validateresearch_group_principal,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
        targetresearch_group_participantKeys: [
          {
            validator: validateresearch_group_participant,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
        subject_name: [
          {
            validator: validatesubject_name,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
        team_name: [
          {
            validator: validateteam_name,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
      },
      layout: {
        labelCol: {span: 4},
        wrapperCol: {span: 14},
      },
      submitting: false,
      research_group_principalSelectionOptions: [],
      // research_group_participantSelectionOptions: [],
      // research_group_reviewerSelectionOptions: [],
      subject_nameSelectionOptions: [],
      team_nameSelectionOptions: [],
      headers: {
        authorization: 'authorization-text',
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {
      this.research_group_principalSelectionOptions = []
      // this.research_group_participantSelectionOptions = []
      // this.research_group_reviewerSelectionOptions = []
      this.subject_nameSelectionOptions = []
      this.team_nameSelectionOptions = []
      this.axios
          .get('/user_management/users')
          .then((res) => {
            const data = res.data
            for (let i = 0; i < data.length; ++i) {
              this.research_group_principalSelectionOptions.push({
                url: data[i].url,
                label: data[i].username,
              })
            }
          })
      this.axios
          .get('/user_management/users')
          .then((res) => {
            const data = res.data
            for (let i = 0; i < data.length; ++i) {
              this.ruleForm.research_group_participants.push({
                key: data[i].url,
                title: data[i].username,
              })
            }
          })
      // this.axios
      //     .get('/user_management/users')
      //     .then((res) => {
      //       const data = res.data
      //       for (let i = 0; i < data.length; ++i) {
      //         this.research_group_reviewerSelectionOptions.push({
      //           url: data[i].url,
      //           label: data[i].username,
      //         })
      //       }
      //     })
      this.axios
          .get('/subject_management/subjects')
          .then((res) => {
            const data = res.data
            for (let i = 0; i < data.length; ++i) {
              this.subject_nameSelectionOptions.push({
                url: data[i].url,
                label: data[i].subject_name,
              })
            }
          })
      this.axios
          .get('/unit_management/teams')
          .then((res) => {
            const data = res.data
            for (let i = 0; i < data.length; ++i) {
              this.team_nameSelectionOptions.push({
                url: data[i].url,
                label: data[i].team_name,
              })
            }
            this.ruleForm.college_name = data.length === 0 ? '' : data[0].url
            if (this.url !== '') {
              this.axios
                  .get(this.url)
                  .then((res) => {
                    const data = res.data
                    this.ruleForm.research_group_name = data.research_group_name
                    this.ruleForm.research_group_principal = data.research_group_principal
                    // this.ruleForm.research_group_participant = data.research_group_participant
                    this.ruleForm.targetresearch_group_participantKeys = data.research_group_participant
                    // this.ruleForm.research_group_reviewer = data.research_group_principal
                    this.ruleForm.subject_name = data.subject_name
                    this.ruleForm.team_name = data.team_name
                  })
                  .catch((error) => {
                    console.log('Error', error.message)
                  })
            }
          })
          .catch((error) => {
            console.log('Error', error.message)
            this.ruleForm.college_name = ''
          })
    },
    handleFinish(values) {
      this.submitting = true
      const formData = new FormData()
      formData.append('research_group_name', values.research_group_name)
      formData.append('research_group_principal', values.research_group_principal)
      // formData.append('research_group_participant', values.research_group_participant)
      this.ruleForm.targetresearch_group_participantKeys.forEach((research_group_participant) => {
        // console.log('test', research_group_participant)
        formData.append("research_group_participant", research_group_participant);
      })
      // if(this.targetresearch_group_participantKeys=='')
      // {
      //   formData.append("research_group_participant", 'none');
      // }
      // formData.append('research_group_reviewer', values.research_group_principal)
      formData.append('subject_name', values.subject_name)
      formData.append('team_name', values.team_name)
      if (this.url !== '') {
        this.axios
            .put(this.url, formData)
            .then(() => {
              this.submitting = false
              message.success('修改成功！')
              this.$emit('operate-success')
            })
            .catch((error) => {
              this.submitting = false
              message.error('修改失败！')
              this.$emit('operate-failed')
              console.log('Error', error.message)
            })
      } else {
        this.axios
            .post('/unit_management/research_groups/', formData)
            .then(() => {
              this.submitting = false
              message.success('添加成功！')
              this.$emit('operate-success')
            })
            .catch((error) => {
              this.submitting = false
              message.error('添加失败！')
              this.$emit('operate-failed')
              console.log('Error', error.message)
            })
      }
    },
    handleChange(nextTargetKeys) {
      this.ruleForm.targetresearch_group_participantKeys = nextTargetKeys
    },
    handleSelectChange(sourceSelectedKeys, targetSelectedKeys) {
      this.ruleForm.selectedresearch_group_participantKeys = [
        ...sourceSelectedKeys,
        ...targetSelectedKeys,
      ]
      // console.log('sourceSelectedKeys: ', sourceSelectedKeys)
      // console.log('targetSelectedKeys: ', targetSelectedKeys)
    },
  },
};
</script>
